package cn.client.navigation

import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.navigation.NavController
import androidx.navigation.NavGraph.Companion.findStartDestination
import androidx.navigation.NavGraphBuilder
import androidx.navigation.NavHostController
import androidx.navigation.NavType
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.navigation
import androidx.navigation.navArgument
import cn.client.navigation.destinations.AppStart
import cn.client.navigation.destinations.AvoidancePainCreateRoute
import cn.client.navigation.destinations.AvoidancePainPageRoute
import cn.client.navigation.destinations.CurrentChatPage
import cn.client.navigation.destinations.DynamicInfoPage
import cn.client.navigation.destinations.EditDynamicPage
import cn.client.navigation.destinations.EditUserInfo
import cn.client.navigation.destinations.EmotionLogCreateRoute
import cn.client.navigation.destinations.EmotionLogPageRoute
import cn.client.navigation.destinations.FriendApplyPages
import cn.client.navigation.destinations.FriendHost
import cn.client.navigation.destinations.FriendInfoPages
import cn.client.navigation.destinations.FriendListPages
import cn.client.navigation.destinations.Message
import cn.client.navigation.destinations.Mindfulness
import cn.client.navigation.destinations.MindfulnessClockInPage
import cn.client.navigation.destinations.MindfulnessExercisePage
import cn.client.navigation.destinations.MindfulnessGroupBuildPage
import cn.client.navigation.destinations.MindfulnessHomePage
import cn.client.navigation.destinations.MindfulnessScorePage
import cn.client.navigation.destinations.Myself
import cn.client.navigation.destinations.Overview
import cn.client.navigation.destinations.SearchUserPages
import cn.client.navigation.destinations.SignInFirst
import cn.client.navigation.destinations.SignInHost
import cn.client.navigation.destinations.SignInSecond
import cn.client.navigation.destinations.SignUpFirst
import cn.client.navigation.destinations.SignUpHost
import cn.client.navigation.destinations.SignUpSecond
import cn.client.navigation.destinations.SignUpThird
import cn.client.navigation.destinations.StartLoading
import cn.client.navigation.destinations.SubjectPage
import cn.client.ui.view.AppScreen
import cn.client.ui.view.StartScreen
import cn.client.ui.view.main.chat.ChatList
import cn.client.ui.view.main.chat.CurrentChat
import cn.client.ui.view.main.chat.friend.FriendInfoPage
import cn.client.ui.view.main.chat.friend.FriendListPage
import cn.client.ui.view.main.chat.friendApply.FriendApplyPage
import cn.client.ui.view.main.chat.friendApply.SearchUserPage
import cn.client.ui.view.main.dynamic.DynamicInfo
import cn.client.ui.view.main.dynamic.DynamicScreen
import cn.client.ui.view.main.dynamic.EditDynamic
import cn.client.ui.view.main.dynamic.subject.SubjectScreen
import cn.client.ui.view.main.mindfulness.MindfulnessClockInScreen
import cn.client.ui.view.main.mindfulness.MindfulnessExerciseScreen
import cn.client.ui.view.main.mindfulness.MindfulnessGroupBuildScreen
import cn.client.ui.view.main.mindfulness.MindfulnessHome
import cn.client.ui.view.main.mindfulness.MindfulnessScoreScreen
import cn.client.ui.view.main.user.UserInfo
import cn.client.ui.view.main.user.UserInfoEdit
import cn.client.ui.view.main.user.avoidancePain.AvoidancePainCreate
import cn.client.ui.view.main.user.avoidancePain.AvoidancePainPage
import cn.client.ui.view.main.user.emotionLog.EmotionLogCreate
import cn.client.ui.view.main.user.emotionLog.EmotionLogPage
import cn.client.ui.view.signIn.SignInFirstPage
import cn.client.ui.view.signIn.SignInSecondPage
import cn.client.ui.view.signUp.SignUpFirstPage
import cn.client.ui.view.signUp.SignUpSecondPage
import cn.client.ui.view.signUp.SignUpThirdPage

/**
 * 主程序的一些目的地配置
 */
@Composable
fun AppNavHost(
    navController: NavHostController,
    modifier: Modifier
    ) {
    NavHost(
        navController = navController,
        startDestination = StartLoading.route,
    ) {

        // 加载页
        composable(route = StartLoading.route){
            StartScreen(navController)
        }

        // 登录&注册页
        composable(route = AppStart.route) {
            AppScreen(navController)
        }
        // 动态页面
        composable(route = Overview.route) {
            DynamicScreen(
                navController = navController,
                onClickDynamicInfo = { dynamicId, authorId ->
                    navController.navigateToSingleDynamicInfo(dynamicId, authorId)
                },
                onClickEditDynamic = { userId->
                    navController.navigateToSingleEditDynamic(userId)
                },
                onClickSubject = { userId->
                    navController.navigateToSingleSubject(userId)
                }
            )
        }

        // 编辑动态
        composable(
            route = EditDynamicPage.route + "/{userId}",
            arguments = listOf(navArgument("userId") { type = NavType.IntType })
        ) { backStackEntry ->
            val userId = backStackEntry.arguments?.getInt("userId") ?: -1
            EditDynamic(userId, navController)
        }

        // 动态信息
        composable(
            route = DynamicInfoPage.route + "/{dynamicId}/{authorId}",
            arguments = listOf(
                navArgument("dynamicId") { type = NavType.IntType },
                navArgument("authorId") { type = NavType.IntType }
            )
        ) { backStackEntry ->
            val dynamicId = backStackEntry.arguments?.getInt("dynamicId") ?: -1
            val authorId = backStackEntry.arguments?.getInt("authorId") ?: -1
            DynamicInfo(dynamicId = dynamicId, authorId = authorId)
        }

        composable(
            route = SubjectPage.route+ "/{userId}",
            arguments = listOf(navArgument("userId") { type = NavType.IntType })
        ) { backStackEntry ->
            val userId = backStackEntry.arguments?.getInt("userId") ?: -1
            SubjectScreen(userId)
        }

        // 消息列表页面
        composable(
            route = Message.route,
            // navigateToCurrentChatPage
        ) {
            ChatList(
                navController = navController,
                onClickChat = { userId, friendId ->
                    navController.navigateToCurrentChatPage(userId = userId, friendId = friendId)
                }
            )
        }

        // 聊天页面
        composable(
            route = CurrentChatPage.route + "/{userId}/{friendId}",
            arguments = listOf(
                navArgument("userId") { type = NavType.IntType },
                navArgument("friendId") { type = NavType.IntType }
            )
        ) { backStackEntry ->
            val userId = backStackEntry.arguments?.getInt("userId") ?: -1
            val friendId = backStackEntry.arguments?.getInt("friendId") ?: -1
            CurrentChat(
                userId = userId,
                friendId = friendId,
                navController = navController
            )
        }

        // 用户页面
        composable(
            route = Myself.route
        ) {
            UserInfo(
                // 跳转修改用户信息页面
                onClickEditUserInfo = {
                    navController.navigateToSingleEditUserInfo(it)
                },
                onClickSignOut = {
                    navController.popBackStack(AppStart.route, true)
                },
                navController = navController
            )
        }

        // 编辑用户信息
        composable(
            route = EditUserInfo.route + "/{userId}",
            arguments = listOf(navArgument("userId") { type = NavType.IntType })
        ) { backStackEntry ->
            val userId = backStackEntry.arguments?.getInt("userId") ?: -1
            UserInfoEdit(userId)
        }

        // 痛苦回避事项页面
        composable(
            route = AvoidancePainPageRoute.route + "/{id}",
            arguments = listOf(navArgument("id") { type = NavType.IntType })
        ){ backStackEntry ->
            val id = backStackEntry.arguments?.getInt("id") ?: -1
            AvoidancePainPage(id, navController)
        }

        // 创建痛苦回避事项页面
        composable(
            route = AvoidancePainCreateRoute.route
        ){
            AvoidancePainCreate(navController)
        }

        // 情绪日志信息页面
        composable(
            route = EmotionLogPageRoute.route + "/{id}",
            arguments = listOf(navArgument("id") { type = NavType.IntType })
        ){ backStackEntry ->
            val id = backStackEntry.arguments?.getInt("id") ?: -1
            EmotionLogPage(id, navController)
        }

        // 创建情绪日志信息页面
        composable(
            route = EmotionLogCreateRoute.route
        ){
            EmotionLogCreate(navController)
        }


        mindfulnessGraph(navController)

        signInGraph(navController)

        signUpGraph(navController)

        friendGraph(navController)

    }
}


/**
 * 登录模块
 */
fun NavGraphBuilder.signInGraph(navController: NavController) {
    navigation(startDestination = SignInFirst.route, route = SignInHost.route) {
        composable(route = SignInFirst.route) {
            SignInFirstPage(navController)
        }
        composable(
            route = SignInSecond.route + "/{account}",
            arguments = listOf(navArgument("account") { type = NavType.StringType })
        ) { backStackEntry ->
            val account = backStackEntry.arguments?.getString("account") ?: ""
            SignInSecondPage(account, navController)
        }
    }
}

/**
 * 正念模块
 */
fun NavGraphBuilder.mindfulnessGraph(navController: NavController) {
    navigation(startDestination = MindfulnessHomePage.route, route = Mindfulness.route) {
        composable(route = MindfulnessHomePage.route) {
            MindfulnessHome(navController)
        }
        // 正念练习页面
        composable(
            route = MindfulnessExercisePage.route + "/{mid}",
            arguments = listOf(navArgument("mid") { type = NavType.IntType })
        ) { backStackEntry ->
            val mid = backStackEntry.arguments?.getInt("mid") ?: -1
            MindfulnessExerciseScreen(mid, navController)
        }
        // 新增正念打卡页面
        composable(
            route = MindfulnessClockInPage.route+ "/{mid}",
            arguments = listOf(navArgument("mid") { type = NavType.IntType })
        ) { backStackEntry ->
            val mid = backStackEntry.arguments?.getInt("mid") ?: -1
            MindfulnessClockInScreen(mid, navController)
        }
        // 新增正念评分页面
        composable(
            route = MindfulnessScorePage.route+ "/{mid}",
            arguments = listOf(navArgument("mid") { type = NavType.IntType })
        ){ backStackEntry ->
            val mid = backStackEntry.arguments?.getInt("mid") ?: -1
            MindfulnessScoreScreen(mid, navController)
        }
        // 正念团体创建页面
        composable(
            route = MindfulnessGroupBuildPage.route
        ){
            MindfulnessGroupBuildScreen(navController)
        }

    }
}


/**
 * 注册模块
 */
fun NavGraphBuilder.signUpGraph(navController: NavController) {
    navigation(startDestination = SignUpFirst.route, route = SignUpHost.route) {
        composable(route = SignUpFirst.route) {
            SignUpFirstPage(navController)
        }
        composable(
            route = SignUpSecond.route + "/{account}",
            arguments = listOf(navArgument("account") { type = NavType.StringType })
        ) { backStackEntry ->
            val account = backStackEntry.arguments?.getString("account") ?: ""
            SignUpSecondPage(account, navController)
        }
        composable(
            route = SignUpThird.route + "/{account}",
            arguments = listOf(navArgument("account") { type = NavType.StringType })
        ) { backStackEntry ->
            val account = backStackEntry.arguments?.getString("account") ?: ""
            SignUpThirdPage(account, navController)
        }
    }
}


/**
 * 好友模块路由
 */
fun NavGraphBuilder.friendGraph(navController: NavController) {
    navigation(startDestination = FriendListPages.route, route = FriendHost.route) {
        composable(
            route = FriendListPages.route) {
            FriendListPage(
                navController = navController,
                onClickFriendInfo = { userId, friendId ->
                    navController.navigate(FriendInfoPages.route + "/${userId}/${friendId}")
                },
                onClickFriendApply = { userId ->
                    navController.navigate(FriendApplyPages.route + "/${userId}")
                },
                onClickSearchUser = { userId->
                    navController.navigate(SearchUserPages.route + "/${userId}")
                }
            )
        }
        composable(
            route = FriendInfoPages.route + "/{userId}/{friendId}",
            arguments = listOf(
                navArgument("userId") { type = NavType.IntType },
                navArgument("friendId") { type = NavType.IntType },
            )
        ) { backStackEntry ->
            val userId = backStackEntry.arguments?.getInt("userId") ?: -1
            val friendId = backStackEntry.arguments?.getInt("friendId") ?: -1
            FriendInfoPage(userId = userId, friendId = friendId, navController)
        }
        composable(
            route = FriendApplyPages.route+ "/{userId}",
            arguments = listOf(navArgument("userId") { type = NavType.IntType })
        ) { backStackEntry ->
            val userId = backStackEntry.arguments?.getInt("userId") ?: -1
            FriendApplyPage(userId = userId, navController)
        }
        composable(
            route = SearchUserPages.route+ "/{userId}",
            arguments = listOf(navArgument("userId") { type = NavType.IntType })
        ) { backStackEntry ->
            val userId = backStackEntry.arguments?.getInt("userId") ?: -1
            SearchUserPage(userId = userId, navController)
        }
    }
}


fun NavHostController.navigateSingleTopTo(route: String) =
    this.navigate(route) {
        /**
         * 解决重复创建副本问题
         */
        popUpTo(
            this@navigateSingleTopTo.graph.findStartDestination().id
        ) {
            // 弹出到导航图的起始目的地，避免在返回堆栈上积累大量目的地
//            saveState = true
            // 包含当前的目的地，防止在跳转回时再次调用该操作
            inclusive = true
        }
        // 确保返回堆栈顶部最多只有给定目的地的一个副本
        launchSingleTop = true
        //确定此导航操作是否应恢复 PopUpToBuilder.saveState 或 popUpToSaveState 属性之前保存的任何状态。
//        restoreState = true
    }


/**
 * 私有辅助扩展函数
 */
private fun NavHostController.navigateToSingleEditUserInfo(userId: Int) {
    this.navigateSingleTopTo("${EditUserInfo.route}/$userId")
}

private fun NavHostController.navigateToSingleEditDynamic(userId: Int) {
    this.navigateSingleTopTo("${EditDynamicPage.route}/$userId")
}

private fun NavHostController.navigateToSingleSubject(userId: Int) {
    this.navigateSingleTopTo("${SubjectPage.route}/$userId")
}

private fun NavHostController.navigateToSingleDynamicInfo(dynamicId: Int, authorId: Int) {
    this.navigateSingleTopTo("${DynamicInfoPage.route}/$dynamicId/$authorId")
}

private fun NavHostController.navigateToCurrentChatPage(userId: Int, friendId: Int) {
    this.navigateSingleTopTo("${CurrentChatPage.route}/$userId/$friendId")
}